package com.becca.cake.service.voucher.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.becca.cake.core.constant.CommonConstants;
import com.becca.cake.core.excel.excelWriter.ExcelInfo;
import com.becca.cake.core.excel.excelWriter.impl.ExcelWriteHandle;
import com.becca.cake.core.exception.ServiceException;
import com.becca.cake.core.freemarker.FreeMarkerHelp;
import com.becca.cake.core.qiniu.FileNameRuleHelp;
import com.becca.cake.core.qiniu.QiNiuGoodsPicTemplate;
import com.becca.cake.core.qiniu.bean.QiNiuResponse;
import com.becca.cake.core.sms.SMSHelper;
import com.becca.cake.core.sms.message.SmsConfirmOrder;
import com.becca.cake.dao.voucher.VoucherDao;
import com.becca.cake.model.advert.AdvertModel;
import com.becca.cake.model.logistic.LogisticStatusModel;
import com.becca.cake.model.system.AdminDO;
import com.becca.cake.model.voucher.VoucherAdvertModel;
import com.becca.cake.model.voucher.VoucherModel;
import com.becca.cake.model.voucher.VoucherOrderDetailsModel;
import com.becca.cake.model.voucher.VoucherOrderExcelModel;
import com.becca.cake.model.voucher.VoucherOrderModel;
import com.becca.cake.model.voucher.VoucherUserPaymentsModel;
import com.becca.cake.service.orders.impl.orderServiceImpl;
import com.becca.cake.service.voucher.IVoucherService;
import com.becca.cake.util.DateUtils;
import com.becca.cake.util.JsonUtil;

@Service
public class VoucherServiceImpl implements IVoucherService{
	
	private static final Logger logger = LoggerFactory.getLogger(orderServiceImpl.class);

	@Autowired
	private VoucherDao voucherDao;
	
	@Override
	public List<VoucherAdvertModel> selectVoucherAdverts(Map<String, Object> map)
			throws Exception {
		return this.voucherDao.selectVoucherAdverts(map);
	}

	@Override
	public Long selectVoucherAdvertsCount(Map<String, Object> map)
			throws Exception {
		return this.voucherDao.selectVoucherCount(map);
	}

	@Override
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void insertOrUpdateVoucherAdvert(
			VoucherAdvertModel voucherAdvertModel, MultipartFile files,
			String fileTempPath, AdminDO adminDo) throws Exception {
		
		// 1.step 广告数据校验
		VoucherAdvertModel.validInsertOrUpdateAdvert(voucherAdvertModel, files);
		
		// 2.step 上传图片
		String voucherAdvertPicPath = "";
		if (!files.isEmpty()) {
			//step3:重新生成图片文件名
			String fileName = FileNameRuleHelp.getVoucherPictureFileName() + "."
							  + FilenameUtils.getExtension(files.getOriginalFilename());
			String filePath = fileTempPath + File.separator + fileName;
			File localFile = new File(filePath);
			files.transferTo(localFile);
			//step4:调用七牛上传图片
            QiNiuResponse response = QiNiuGoodsPicTemplate.uploadFile(localFile, fileName);
            if (response.isSuccess()) {
            	voucherAdvertPicPath = QiNiuGoodsPicTemplate.getDownloadUrl(response.key);
            } else {
                throw new ServiceException(VoucherAdvertModel.PICTURE_UPDLOAD_FAILED);
            }
            // step5:删除本地图片
            localFile.delete();
		}
		if (StringUtils.isNotEmpty(voucherAdvertPicPath)) {
            voucherAdvertModel.setAdvPicPath(voucherAdvertPicPath);
        }
        if (voucherAdvertModel.getAdvStatus() == null) {
            voucherAdvertModel.setAdvStatus(AdvertModel.ADV_STATUS_NOMAL);
        }
        // step6:添加或修改广告
        if (voucherAdvertModel.getId() == null) {// 新增
        	voucherAdvertModel.setCreatedName(adminDo.getTrueName());
            this.voucherDao.insertVoucherAdvert(voucherAdvertModel);
        } else {// 修改
        	voucherAdvertModel.setUpdatedName(adminDo.getTrueName());
            this.voucherDao.updateVoucherAdvert(voucherAdvertModel);
        }
	}

	@Override
	public VoucherAdvertModel selectVoucherAdvertById(Integer advertId) {
		VoucherAdvertModel.validAdvId(advertId);
		return this.voucherDao.selectVoucherAdvertById(advertId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void updateAdvStatusById(Map<String, Object> map) throws Exception {
		Integer advertId = Integer.valueOf(map.get("advertId").toString());
		String status = String.valueOf(map.get("status"));
		// 1.step 校验
		VoucherAdvertModel.validAdvStatus(advertId, status);
		VoucherAdvertModel va = voucherDao.selectVoucherAdvertById(advertId);
		String advNowStatus = va.getAdvStatus().toString();
		if (status.equals(advNowStatus)&&VoucherAdvertModel.ADV_STATUS_FORBIDDEN.equals(status)) {
			throw new ServiceException(VoucherAdvertModel.ADVERT_STATUS_FORBIDDEN_EXIST);
		}else if (status.equals(advNowStatus)
                && VoucherAdvertModel.ADV_STATUS_NOMAL.toString().equals(status)) {
         throw new ServiceException(VoucherAdvertModel.ADVERT_STATUS_NOMAL_EXIST);
     }
		// 2.step 修改广告状态
		this.voucherDao.updateAdvStatusById(map);
	}

	@Override
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void updateVoucherOrders(String jsonList) throws Exception {
		List<VoucherAdvertModel> list = JsonUtil.returnObjectList(jsonList, VoucherAdvertModel.class);
		VoucherAdvertModel.validUpdateOrders(list);
        this.voucherDao.updateVoucherOrders(list);
	}

	@Override
	public List<VoucherUserPaymentsModel> selectVoucherPayments(
			Map<String, Object> map) throws Exception {
		return this.voucherDao.selectVoucherPayments(map);
	}

	@Override
	public Long selectVoucherPaymentsCount(Map<String, Object> map)
			throws Exception {
		return this.voucherDao.selectVoucherPaymentsCount(map);
	}

	@Override
	public List<VoucherModel> selectVoucher(Map<String, Object> map)
			throws Exception {
		return this.voucherDao.selectVoucher(map);
	}

	@Override
	public Long selectVoucherCount(Map<String, Object> map) throws Exception {
		return this.voucherDao.selectVoucherCount(map);
	}

	@Override
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void insertOrUpdateVoucher(VoucherModel voucherModel, AdminDO adminDo) throws Exception {
		if (voucherModel.getId() == null ) {//添加
			voucherModel.setCreatedName(adminDo.getTrueName());
			this.voucherDao.insertVoucher(voucherModel);
		}else {//修改
			voucherModel.setUpdatedName(adminDo.getTrueName());
			this.voucherDao.updateVoucher(voucherModel);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void updVoucherStatusById(Integer voucherId, Integer voucherStatus,
			String trueName) throws ServiceException {
		VoucherModel.validVoucherIdNull(voucherId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("voucherId", voucherId);
		map.put("voucherStatus", voucherStatus);
		map.put("userName", trueName);
		VoucherModel voucherModel =  this.voucherDao.selectVoucherById(voucherId);
		if (voucherModel ==null) {
			throw new ServiceException(VoucherModel.VOUCHER_NOT_EXISTS);
		}
		Long isVoucherDown = this.voucherDao.isVoucherExist(map);
		if (isVoucherDown !=0) {
			throw new ServiceException(VoucherModel.VOUCHER_STATUS_DOWN_EXIST);
		}
		this.voucherDao.updVoucherStatusById(map);
	}

	@Override
	public VoucherModel selectVoucherById(Integer voucherId) throws Exception {
		return this.voucherDao.selectVoucherById(voucherId);
	}


	@Override
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void updateVoucherOrder(String jsonList, String userName)
			throws ServiceException {
		//step1:请求参数
        List<VoucherModel> list = JsonUtil.returnObjectList(jsonList, VoucherModel.class);
        VoucherModel.validVoucherOrder(list);
        //step2:封装请求参数
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("goodsList", list);
        map.put("userName", userName);
        this.voucherDao.updateVoucherOrder(map);
		
	}

	@Override
	public List<VoucherOrderModel> selectVoucherOrders(Map<String, Object> map)
			throws ServiceException
	{
		return this.voucherDao.selectVoucherOrder(map);
	}

	@Override
	public Long selectVoucherOrdersCount(Map<String, Object> map)
			throws ServiceException
	{
		return this.voucherDao.selectVoucherOrderCount(map);
	}

	@Override
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void updateVoucherOrder(VoucherOrderModel voucherOrderModel)
			throws ServiceException
	{
		VoucherOrderModel.validUpdateOrder(voucherOrderModel);
		this.voucherDao.updateVoucherOrderModel(voucherOrderModel);
	}

	@Override
	public VoucherOrderModel findVoucherOrderById(Integer orderId)
			throws Exception
	{
		VoucherOrderModel.validOrderIdNull(orderId);
		return this.voucherDao.findVoucherOrderById(orderId);
	}

	@Override
	public List<VoucherOrderDetailsModel> selectVoucherDetailsByOrderId(
			Integer orderId) throws Exception
	{
		VoucherOrderModel.validOrderIdNull(orderId);
		return this.voucherDao.selectDetailsByOrderId(orderId);
	}

	@Override
	public void updateVoucherOrderStatus(Map<String, Object> paramMap)
			throws ServiceException
	{
		//step1:获取封装数据
        String orderIds = String.valueOf(paramMap.get("orderIds"));
        Byte orderStatus = Byte.valueOf(String.valueOf(paramMap.get("orderStatus")));
        String statusName = String.valueOf(paramMap.get("statusName"));
        String userName = String.valueOf(paramMap.get("userName"));
        //step2:数据校验
        VoucherOrderModel.validateUpdateOrderStatus(orderIds, orderStatus, statusName);
        //step3:查询订单状态
        String[] orderIdArray = orderIds.split(",");
        for (String orderIdStr : orderIdArray) {
            Integer orderId = Integer.valueOf(orderIdStr);
            
            VoucherOrderModel voucherOrderModel = this.voucherDao.selectOrderById(orderId);
            if (voucherOrderModel == null) {
                throw new ServiceException(VoucherOrderModel.ORDER_NO_EXISTS);
            }
            //step4:校验订单状态
            if (orderStatus <= voucherOrderModel.getOrderStatus().intValue()) {
                throw new ServiceException(VoucherOrderModel.ORDER_STARUS_EXCEPTION);
            }
            //step5:修改订单状态
            VoucherOrderModel orderMo = new VoucherOrderModel();
            orderMo.setId(orderId);
            orderMo.setOrderStatus(Byte.valueOf(String.valueOf(orderStatus)));
            orderMo.setUpdatedName(userName);
            this.voucherDao.updateOrderStatus(orderMo);
            //step7:已确认订单推送通知消息
            //消息推送
            if (VoucherOrderModel.ORDER_STATUS_SENDED == orderStatus) {//已发货短信提醒
                String phone = voucherOrderModel.getConsignPhone();
                if (StringUtils.isNotEmpty(phone)) {
                	SmsConfirmOrder sms = new SmsConfirmOrder(phone, voucherOrderModel.getVoucherCode());
                    if (SMSHelper.sendMessage(sms)) {
                        logger.info("订单:" + voucherOrderModel.getVoucherCode() + "已发货");
                    }
                }
            }
        }
	}

	@Override
	public List<String> printThermalOrder(String htmlFilePath,
			Map<String, Object> map) throws Exception
	{
		List<String> returnList = new ArrayList<String>();
        //step1:获取请求数据
        String orderId = String.valueOf(map.get("orderId"));
        //step2:数据校验
        VoucherOrderModel.validatePrintThermalValidate(orderId);
        //step3:查询订单信息
        List<VoucherOrderModel> listOrder = this.voucherDao.selectPrintThermalOrder(map);
        //step4:查询订单明细
        if (listOrder != null && listOrder.size() > 0) {
            Map<String, Object> orderDetailMap = new HashMap<String, Object>();
            for (VoucherOrderModel voucherOrderModel : listOrder) {

                orderDetailMap.put("orderId", voucherOrderModel.getId());
                //订单编号条形码
                String orderCodeUrl = CommonConstants.PROJECT_PATH + "/barcode?msg="
                                      + voucherOrderModel.getVoucherCode();

                List<VoucherOrderDetailsModel> listOrderDetailsModels = this.voucherDao
                    .selectOrderDetailByOrderId(orderDetailMap);
                //step7:每个商品打印一个热敏信息
                if (listOrderDetailsModels != null && listOrderDetailsModels.size() > 0) {
                    for (int i = 0, n = listOrderDetailsModels.size(); i < n; i++) {
                    	VoucherOrderDetailsModel detailsModel = listOrderDetailsModels.get(i);
                        for (int j = 0; j < detailsModel.getVoucherNumber(); j++) {
                            String htmlCode = String.valueOf(i) + String.valueOf(j);
                            String filePostfix = voucherOrderModel.getVoucherCode() + htmlCode + ".html";
                            //本地html保存路径
                            String localHtmlPath = htmlFilePath + File.separator + filePostfix;
                            Map<String, Object> mapParam = new HashMap<String, Object>();
                            mapParam.put("orders", voucherOrderModel);
                            mapParam.put("orderDetail", detailsModel);
                            mapParam.put("voucherNumber", 1);
                            mapParam.put("orderCodeUrl", orderCodeUrl);
                            boolean flag = FreeMarkerHelp.makeHtml("thetmalPrint.ftl",
                                localHtmlPath, mapParam);
                            if (flag) {
                                //静态页面可访问地址
                                String htmlUrl = "/html/" + filePostfix;
                                returnList.add(htmlUrl);
                            }
                        }
                    }
                }
            }
        }
        return returnList;
	}

	@Override
	public List<VoucherOrderModel> selectHandOverVoucherOrders(String orderIds)
			throws ServiceException
	{
		List<VoucherOrderModel> orderList = this.voucherDao.selectHandOverOrders(orderIds);
        // step3:为每个订单设置对应的订单详情列表
        for (int i = 0; i < orderList.size(); i++) {
            List<VoucherOrderDetailsModel> orderDetailList = this.voucherDao
                .selectHandOverOrderDetails(orderList.get(i).getId());
            orderList.get(i).setVoucherOrderList(orderDetailList);
        }
        return orderList;
	}

	@Override
	public List<VoucherOrderDetailsModel> selectHandOverVoucherOrderDetails(
			Integer orderId) throws ServiceException
	{
		return this.voucherDao.selectHandOverOrderDetails(orderId);
	}

	@Override
	public void exportOrdersToExcel(HttpServletRequest request,
			HttpServletResponse response, List list )
			throws ServiceException
	{
		ExcelInfo info = new ExcelInfo();
        info.setColumnHeader("订单组号,商户名,商户合同,客户订单号 ,商品名称,单价,数量,商品备注,订单应收总金,城市,收货人 ,省,市,区,收货地址,手机号码,固定电话,支付方式,配送备注");
        info.setFeilds(",,,voucherCode,voucherName,voucherPrice,voucherNumber,,,,consignee,,,,consignAddress,consignPhone,,payWays,remark");
        info.setDatas(list);
        info.setSheetName("订单详情信息");
        info.setFileName(DateUtils.getStringToday() + "订单详情单");
        ExcelWriteHandle.getInstance().writeEcxcel(info, request, response);
		
	}

	@Override
	public List<VoucherOrderExcelModel> selectOrderExcelModel(String orderIds)
			throws ServiceException
	{
		return this.voucherDao.selectOrderExcelModel(orderIds);
	}

	@Override
	public void updateOrderLogisticsMessage(Map<String, Object> map)
			throws ServiceException
	{
		 //step1:获取请求信息
        Integer logisticId = Integer.valueOf(String.valueOf(map.get("logisticId")));
        String logisticMessage = String.valueOf(map.get("logisticMessage"));
        //step2:数据验证
        LogisticStatusModel.validateOrderLogisticsMessageParam(logisticId, logisticMessage);
        //step3:修改物流信息
        this.voucherDao.updateOrderLogisticsMessage(map);
	}

	@Override
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void updRefuseReceiveOrder(Map<String, Object> map)
			throws ServiceException
	{
	}

	@Override
	public Map<String, Object> selectDayOrders() throws Exception
	{
		//返回参数信息
        Map<String, Object> returnMap = new HashMap<String, Object>();
        String orderStatus = VoucherOrderModel.getDayOrderStatus();
        //step1:获取前一天和今天日期时间
        String preDayTime = DateUtils.getOneTimeDate(-1, 16);
        String nowDayTime = DateUtils.getOneTimeDate(0, 16);
        //step2:查询订单信息
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("orderStatus", orderStatus);
        paramMap.put("preDayTime", preDayTime);
        paramMap.put("nowDayTime", nowDayTime);
        List<VoucherOrderModel> orderList = this.voucherDao.selectDayOrders(paramMap);
        if (orderList != null && orderList.size() > 0) {
            // step3:订单详情
            Double totalAmountSum = 0.00; // 订单总额
            Double payAmountSum = 0.00; // 支付总额
            Integer voucherNumberSum = 0; // 商品总数
            for (VoucherOrderModel orderInfo : orderList) {
                List<VoucherOrderDetailsModel> orderDetailList = this.voucherDao
                    .selectDetailsByOrderId(orderInfo.getId());
                orderInfo.setVoucherOrderList(orderDetailList);
                totalAmountSum += orderInfo.getTotalAmount();
                payAmountSum += orderInfo.getPayAmount();
                voucherNumberSum += orderInfo.getVoucherNumber();
            }

            // step4:模板参数
            Map<String, Object> orderMap = new HashMap<String, Object>();
            orderMap.put("orderList", orderList);
            orderMap.put("preDayTime", preDayTime);
            orderMap.put("nowDayTime", nowDayTime);
            orderMap.put("totalAmountSum", totalAmountSum);
            orderMap.put("payAmountSum", payAmountSum);
            orderMap.put("voucherNumberSum", voucherNumberSum);
            String templateHtml = FreeMarkerHelp.getTemplateHtml(orderMap, "dayMessage.ftl");
            returnMap.put("isOrderCount", true);
            returnMap.put("templateHtml", templateHtml);
        } else {
            returnMap.put("isOrderCount", false);
        }
        return returnMap;
	}

	@Override
	public Map<String, Object> statisticsOrderReport() throws Exception
	{
		return null;
	}

	@Override
	public void insertVoucherOrderPicture(VoucherOrderModel voucherOrderModel,
			MultipartFile files, String fileTempPath, AdminDO adminDo)
			throws Exception
	{
		// 1.step 广告数据校验
			VoucherOrderModel.validInsertOrderPictuer(voucherOrderModel, files);
				
				// 2.step 上传图片
				String voucherOrderPicPath = "";
				if (!files.isEmpty()) {
					//step3:重新生成图片文件名
					String fileName = FileNameRuleHelp.getVoucherPictureFileName() + "."
									  + FilenameUtils.getExtension(files.getOriginalFilename());
					String filePath = fileTempPath + File.separator + fileName;
					File localFile = new File(filePath);
					files.transferTo(localFile);
					//step4:调用七牛上传图片
		            QiNiuResponse response = QiNiuGoodsPicTemplate.uploadFile(localFile, fileName);
		            if (response.isSuccess()) {
		            	voucherOrderPicPath = QiNiuGoodsPicTemplate.getDownloadUrl(response.key);
		            } else {
		                throw new ServiceException(VoucherOrderModel.PICTURE_UPDLOAD_FAILED);
		            }
		            // step5:删除本地图片
		            localFile.delete();
				}
				if (StringUtils.isNotEmpty(voucherOrderPicPath)) {
					voucherOrderModel.setDeliveryPicture(voucherOrderPicPath);
		        }
//		        if (voucherOrderModel.getAdvStatus() == null) {
//		        	voucherOrderModel.setAdvStatus(AdvertModel.ADV_STATUS_NOMAL);
//		        }
		        // step6:添加或修改广告
		        
		        	//voucherOrderModel.setCreatedName(adminDo.getTrueName());
		        this.voucherDao.insertVoucherOrderPicture(voucherOrderModel);
		      
		
	}

	

}
